/*
 * 
 * Copyright 2010 David H Pollack
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 * 
 * 
 */

package com.dhpollack.rotogss.servlets;

import static com.google.appengine.api.labs.taskqueue.TaskOptions.Builder.url;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.datanucleus.store.appengine.query.JDOCursorHelper;

import com.dhpollack.rotogss.data.RotoGSSLeagueXml;
import com.dhpollack.rotogss.helper.PMF;
import com.google.appengine.api.datastore.Cursor;
import com.google.appengine.api.labs.taskqueue.Queue;
import com.google.appengine.api.labs.taskqueue.QueueFactory;

/**
 * @author davidpl
 *
 */
public class CronStandingsServlet extends HttpServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -7219866310778523286L;

	protected void service(HttpServletRequest req, HttpServletResponse resp) 
    throws ServletException, IOException {

		int users_per_pass = 100;
		
        Queue queue = QueueFactory.getDefaultQueue();

        boolean callSelf = false;
		
		String lastCursorString = (String) req.getAttribute("cursor");
		
		Integer n = (Integer) req.getAttribute("nth"); 
		
		if(n == null) {
			n = 1;
		}
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		Query query = pm.newQuery(RotoGSSLeagueXml.class);
		if(lastCursorString != null) {
			log("Found Cursor: " + lastCursorString);
	        Cursor lastCursor = Cursor.fromWebSafeString(lastCursorString);
	        Map<String, Object> extensionMap = new HashMap<String, Object>();
	        extensionMap.put(JDOCursorHelper.CURSOR_EXTENSION, lastCursor);
	        query.setExtensions(extensionMap);
		} else {
			log("Didn't find cursor");
		}
		query.setRange(0, users_per_pass);
		List<RotoGSSLeagueXml> results;
		try {
			results = (List<RotoGSSLeagueXml>) query.execute();
			if(results.iterator().hasNext()) {
				for(RotoGSSLeagueXml lxml : results) {
					String league = lxml.getLeagueKey().getName();
					log("League: " + league);
                    queue.add(url("/admin/yStoreStanding").param("league", league));

				}
				callSelf = true;
			} else {
				log("LeagueXml not found.");
				callSelf = false;
			}
		} finally {
	        query.closeAll();
		}

		if(callSelf) {
	    	log("Calling self for the "+ n + " time.");
	    	n++;
            Cursor currentCursor = JDOCursorHelper.getCursor(results);
            String currentCursorString = currentCursor.toWebSafeString();
	    	req.setAttribute("nth", n);
	    	req.setAttribute("cursor", currentCursorString);
	        req.getRequestDispatcher(req.getServletPath()).include(req, resp);
	    	
	    }
	}


}
